<!--
 * @Date: 2023-10-13 10:47:59
 * @LastEditTime: 2023-10-25 13:19:38
 * 介绍:
-->

<cfg lang="json">
{
  "navigationBarTitleText": "主页",
  "enablePullDownRefresh": false,
  "navigationStyle": "custom"
}
</cfg>

<script setup lang="ts">
import router from "@/hooks/router";
import { uniShowModal } from "@/sdk/rewriteUni";
import useSysStore from "@/store/useSysStore";
import {
  apiCreateRoom,
  apiJoinRoom,
  CreateRoom,
  JoinRoom,
  apiDelRoom,
} from "@/api/module/call";
import { randomNum } from "@/utils/tools/generate";
import { AuthData } from "../metting/components/mix";
import { metting } from "@/enum/pubsubKey";
import { InitState } from "../metting/components/mix";
import { requset_uniapp_kill_service_plugin } from "@/sdk/sdk";

const sysStore = useSysStore();
//#ifdef APP-PLUS
const keepAlive = requset_uniapp_kill_service_plugin();
const isLimit = keepAlive.checkIfLimited()?.isLimit;

if (isLimit === true && sysStore.setting.disableBgLimitAlert !== true) {
  uniShowModal({
    title: "APP无后台运行权限",
    content: "为了您更好的体验本产品，请您在后台配置中选择无限制",
  })
    .then(keepAlive.requestIgnoreLimit)
    .catch(() => {
      uniShowModal({
        title: "点击(不再提示)后不再提示",
        content: "您仍可以在页面下方找到开启后台运行权限",
        cancelText: "不再提示",
      }).catch(() => (sysStore.setting.disableBgLimitAlert = true));
    });
}
//#endif

onLoad(() => {
  uni.hideTabBar();
});
async function createRoom() {
  const { authCode } = sysStore.setting;
  let title = "请输入授权码(必填)";
  let content = "";
  if (authCode) {
    title = "更新授权码(选填)";
    content = `已授权的授权码：${authCode}`;
  }
  let placeholderText = title;
  let { content: code } = await uniShowModal({
    title,
    placeholderText,
    content,
    showCancel: false,
    editable: true,
  });
  code ||= authCode;
  if (!code) return;
  const res = await apiCreateRoom({ code });
  if (!res) return;
  sysStore.setRequestBaseData({ _token: res.turn.login_code });
  sysStore.setting.authCode = code;
  toMetting(res, {
    initUseCamera: false,
    initUseScreen: false,
    disableScreenPreview: true,
    manger: res.user_id,
    ...res.settings,
  });
  uni.$once(metting.unLoad, (roomName) => {
    apiDelRoom({ channel: roomName || code! });
  });
}

async function joinRoom() {
  let title = "请输入房间号";
  const { content: channel } = await uniShowModal({
    title,
    placeholderText: title,
    showCancel: false,
    editable: true,
  });
  if (!channel) return;
  const res = await apiJoinRoom({ channel });
  if (!res) return;
  sysStore.setRequestBaseData({ _token: res.login_code });
  toMetting(
    { ...res, channel },
    {
      initUseCamera: false,
      initUseScreen: true,
      disableScreenPreview: true,
      manger: res.manger,
      ...res.settings,
    }
  );
}
const inRefresh = ref(false);
function refresh() {
  inRefresh.value = true;
  uni.showLoading({
    title: "正在为您选择最优线路...",
  });
  setTimeout(() => {
    uni.hideLoading();
    inRefresh.value = false;
  }, randomNum(500, 5000));
}
function disconnected() {
  uni.hideLoading();
  inRefresh.value = false;
}

/**
 *
 * @param res 进入房间认证数据
 * @param extraInfo
 */
function toMetting(res: Omit<CreateRoom.Res, "turn">, initState?: InitState) {
  const { channel, token, appid, user_id, list_id } = res;
  const data: AuthData = {
    list_id,
    roomName: channel.toString(),
    token,
    appKey: appid,
    userID: user_id.toString(),
  };
  const json = JSON.stringify({
    data,
    initState,
  });
  router.push("src/pages/metting/metting.nvue", {
    query: {
      json,
    },
  });
}

onMounted(refresh);
</script>

<template>
  <CpageView :use-custom-navbar="false">
    <view class="content flex-J-SB flex-A-C flex-col">
      <view class="header T-A-R fill-W">
        <CinRefresh :inRefresh="inRefresh" @click="refresh" />
      </view>
      <view @click="createRoom" class="createBtn active">创建房间</view>
      <view @click="joinRoom" class="joinBtn active">加入房间</view>
      <view>
        <!-- #ifdef APP-PLUS -->
        <view
          v-if="isLimit === true"
          @click="keepAlive.requestIgnoreLimit()"
          class="T-S-sm"
        >
          前往开启后台运行权限
        </view>
        <!-- #endif -->
      </view>
    </view>
    <RnoNetwork @connected="refresh" @disconnected="disconnected" />
  </CpageView>
</template>
<style lang="scss" scoped>
.content {
  height: var(--page-H);
}
.createBtn,
.joinBtn {
  $size: 200rpx;
  height: $size;
  width: $size;
  line-height: $size;
  text-align: center;
  border-radius: 24rpx;
  color: var(--C-B1);
}
.createBtn {
  background-color: #0f46f8;
}
.joinBtn {
  background-color: #680ff8;
}
</style>
